public class SpiralMatrixII {
    public static int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];

        int startx = 0;
        int starty = 0;

        int xVisited = 0;
        int yVisited = 0;

        int[] x = {1,0,-1,0};
        int[] y = {0,1,0,-1};

        int direction = 0;
        int step = 0;
        int candidateMove = 0;

        for(int i=1;i<=n*n;i++){
            if(x[direction]==0)
                candidateMove = n - yVisited;
            else
                candidateMove = n - xVisited;

            if(candidateMove<=0)
                break;

            //System.out.println(startx + " " + starty + " " + candidateMove);
            matrix[starty][startx] = i;

            step++;

            if(candidateMove == step){
                yVisited += x[direction] == 0 ? 0: 1;
                xVisited += y[direction] == 0 ? 0: 1;
                direction = (direction + 1)%4;

                step = 0;
            }

            startx += x[direction];
            starty += y[direction];
        }
        /*
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[0].length;j++){
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
            }*/
        return matrix;
    }
    
    public static void main(String[] args) {
        for(int i=0;i<6;i++)
            generateMatrix(i);
    }
}
